package com.fgba.express.config;

import com.fgba.express.comm.GlobalConst;
import com.fgba.express.security.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author fgba
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private LoginFailureHandler failureHandler;

    @Resource
    private WeChatLoginFailureHandler weChatLoginFailureHandler;

    @Resource
    private CustomLoginSuccessHandler customLoginSuccessHandler;

    @Resource
    private WeChatLoginSuccessHandler weChatLoginSuccessHandler;

    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Resource
    private JwtAccessDeniedHandler jwtAccessDeniedHandler;

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private LogoutHandler logoutHandler;

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public static final String[] URL_WHITELIST = {
            "/favicon.ico",
            "/login", "/weChatLogin", "/user/bind",
            "/logout",
            "/doc.html","/swagger/**","/swagger-ui.html",
            "/webjars/**","/v2/**","/v2/api-docs-ext/**", "/swagger-resources/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        WeChatAuthenticationFilter weChatFilter = weChatAuthenticationFilter();
        CustomAuthenticationFilter customAuthenticationFilter = customAuthenticationFilter();
        http.addFilterBefore(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(weChatFilter, UsernamePasswordAuthenticationFilter.class)
                .cors().and().csrf().disable()
                //登录配置
                .formLogin()
                // 登录需要经过的url请求
                .loginProcessingUrl("/login")
                .loginProcessingUrl("/weChatLogin")
                //登出配置
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(logoutHandler)
                .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                // 不会创建 session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //拦截规则配置
                .and()
                .authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(dynamicSecurityMetadataSource());
                        object.setAccessDecisionManager(dynamicAccessDecisionManager());
                        return object;
                    }
                })
                .anyRequest().authenticated()
                //异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                //配置自定义过滤器
                .and()
                // 登录校验过滤器
                .addFilter(jwtAuthenticationFilter())
                .headers()
                // 增加csp防xss攻击    frame-ancestors 针对frame的加载策略     default-src 针对默认加载策略 object-src 针对插件的加载策略
                .contentSecurityPolicy(
                        "frame-ancestors 'self'; default-src 'self' 'unsafe-inline' 'unsafe-eval' *.aliyuncs.com *.baidu.com *.bdimg.com ;object-src 'self'")
        ;

    }

    @Bean
    public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
        return new DynamicAccessDecisionManager();
    }

    @Bean
    public DynamicSecurityMetadataSource  dynamicSecurityMetadataSource () {
        return new DynamicSecurityMetadataSource ();
    }

    /**
     * 添加用户名和密码登陆验证的过滤器
     */
    @Bean
    public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setAuthenticationSuccessHandler(customLoginSuccessHandler);
        filter.setAuthenticationFailureHandler(failureHandler);
        return filter;
    }

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(weChatAuthenticationProvider());
    }

    @Bean
    public WeChatAuthenticationProvider weChatAuthenticationProvider() {
        return new WeChatAuthenticationProvider();
    }

    /**
     * 添加微信openid登陆验证的过滤器
     */
    @Bean
    public WeChatAuthenticationFilter weChatAuthenticationFilter() throws Exception {
        WeChatAuthenticationFilter filter = new WeChatAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.setAuthenticationSuccessHandler(weChatLoginSuccessHandler);
        filter.setAuthenticationFailureHandler(weChatLoginFailureHandler);
        return filter;
    }
}
